local config = require "config"
local host = config.redis.host
local port = config.redis.port
local auth = config.redis.auth

-------------------------------------------------------------------------------
---! 对外接口
-------------------------------------------------------------------------------
local function consumer(linda)
    local redis = require "utils.redis"

    while true do
        if cancel_test() then
            return
        end

        local ok, failmsg = redis.create(host, port, auth)
        if ok then
            redis.del(config.server.game_channel)
            break
        end

        spdlog.error("redis", "failmsg : " .. failmsg)
        sleep(3)
    end

    spdlog.debug("redis", "[%s:%s@%s consumer] start ...", host, port)
    while not cancel_test() do repeat
        local reply = redis.brpop(config.server.login_channel, config.server.game_channel, 3)
        if type(reply) ~= "table" or #reply ~= 2 then
            redis.ping()
            break
        end

        if reply[1] and reply[2] then
            linda:send(reply[1], table.pack(reply[2]))
        end
    until true end

    redis.destory()
    spdlog.debug("redis", "[%s:%s consumer] quit ...", host, port)
end

local function producer(linda)
    local redis = require "utils.redis"

    while true do
        if cancel_test() then
            return
        end

        local ok, failmsg = redis.create(host, port, auth)
        if ok then
            break
        end

        spdlog.error("redis", "failmsg : " .. failmsg)
        sleep(3)
    end

    spdlog.debug("redis", "[%s:%s@%s producer] start ...", host, port)
    while not cancel_test() do repeat
        local key, reply = linda:receive(3.0, "client_channel")
        --!通用redis 额外通用存储
        if key == "common_channel" then

        end

        if key ~= "client_channel" then
            redis.destory()
            break
        end

        if type(reply) ~= "table" or #reply ~= 2 then
            redis.destory()
            break
        end

        redis.lpush(reply[1], reply[2])
    until true end

    redis.destory()
    spdlog.debug("redis", "[%s:%s producer] quit ...", host, port)
end

-------------------------------------------------------------------------------
---! 对外接口
-------------------------------------------------------------------------------
register_post_init(function()
    SERVICE_D:create("redis", consumer)
    SERVICE_D:create("redis", producer)
end)
